<template>
	<view class="root">
		<view :style="{ margin: `30rpx` }">
			<image
				:style="{ width: `100%`, height: `300rpx` }"
				class="br-10"
				src="/static/images/pic-joinPanda.png"
				mode="aspectFill"
			/>
		</view>

		<view class="fd-row jc-sb fs-30" :style="{ margin: `12rpx 30rpx 36rpx` }">
			<label
				v-for="(tab, key) in tabs"
				:key="key"
				@click="switchTopTabBar(key)"
				:class="[{ active: tabKey === key }, 'tab jc-center']"
			>
				我是{{ tab }}
			</label>
		</view>

		<view
			:style="{
				margin: `30rpx`,
				boxShadow: `0 0 16rpx 0 rgba(0, 0, 0, 0.15)`,
			}"
			class="br-10"
		>
			<view
				v-for="(option, optionKey) in viewModel[tabKey].options"
				:key="optionKey"
				:style="{
					padding: `18rpx 30rpx`,
					borderBottom: `1rpx solid #eee`,
				}"
				class="fd-row ai-center"
			>
				<image
					class="width-34 height-34 mr-36"
					:src="`/static/images/icon-${option.icon}.png`"
					mode="aspectFit"
				/>
				<input
					v-if="option.el === 'input'"
					:value="option.value"
					:type="option.type"
					:placeholder="option.placeholder"
					:maxlength="option.maxlength"
					:disabled="!!viewModel[tabKey].status"
					@input="operation(optionKey, $event)"
					class="f1 input fs-24 height-54"
					placeholder-class="color-999"
				/>

				<view v-if="option.el === 'image'" class="f1 fd-row">
					<view class="f1 fd-row">
						<image
							v-for="(photo, photoIndex) in option.value"
							:key="photoIndex"
							:src="photo"
							@click="tapPhotos(optionKey, photoIndex)"
							mode="aspectFill"
							class="width-100 height-100 mr-20 br-10"
						/>
						<image
							v-if="option.value.length < option.maxlength"
							class="width-100 height-100 mr-20 br-10"
							:src="`/static/images/pic-upload_${option.icon}.png`"
							mode="aspectFill"
							@click="operation(optionKey)"
						/>
					</view>

					<text class="fs-20 color-999 as-end">
						{{ option.placeholder }}
					</text>
				</view>
			</view>
		</view>
		<text
			:style="{
				margin: `0 30rpx`,
			}"
			class="fs-26 color-999"
			v-if="viewModel[tabKey].desc"
		>
			{{ viewModel[tabKey].desc }}
		</text>
		<button
			:plain="true"
			:style="{ margin: `80rpx 30rpx 50rpx` }"
			hover-class="tap-hover"
			class="bgc-3ec483 border-none br-10 color-fff br-10 fs-30 lh-3"
			:disabled="!!viewModel[tabKey].status"
			@click="publish"
		>
			{{
				[` 立即申请成为${tabs[tabKey]}`, "已通过审核", "审核中"][
					viewModel[tabKey].status || 0
				]
			}}
		</button>
	</view>
</template>

<script lang="ts">
	import { $config } from "@/common";
	import { sleep, Storage } from "@/libs/utils";
	import { Vue, Component } from "vue-property-decorator";

	@Component
	export default class JoinPanda extends Vue {
		// component property
		tabs: AnyObject = {
			driver: "司机",
			transporter: "搬运工",
			installer: "安装工",
		};
		tabKey: string = "driver";

		viewModel: AnyObject = {};

		onLoad() {
			this.$request.get("/user/roleinfo").then(({ data }) => {
				const common = JSON.stringify({
					realName: {
						name: "name",
						el: "input",
						type: "text",
						value: data.name,
						data: data.name,
						maxlength: 9,
						placeholder: "请填写你的真实姓名",
						icon: "user_green",
					},
					phoneNumber: {
						name: "phone",
						el: "input",
						type: "number",
						value: data.phone,
						data: data.phone,
						maxlength: 11,
						placeholder: "请填写你的手机号码",
						icon: "phone_orange",
					},
					idNumber: {
						name: "idcard",
						el: "input",
						type: "number",
						value: data.idcard,
						data: data.idcard,
						maxlength: 18,
						placeholder: "请填写你的身份证号",
						icon: "idCard",
					},
				});

				this.viewModel = {
					driver: {
						status: data.driver_status,
						options: {
							...JSON.parse(common),
							drivingLicense: {
								name: "driver_images",
								el: "image",
								value: data.driver_images,
								maxlength: 2,
								placeholder: "*上传驾驶证正副页*",
								icon: "drivingLicense",
							},
						},
						desc: data.driver_desc,
					},
					transporter: {
						status: data.hamal_status,
						options: {
							...JSON.parse(common),
							transporterJobCertificate: {
								name: "hamal_images",
								el: "image",
								value: data.hamal_images,
								maxlength: 2,
								placeholder: "*上传职业证正副页*",
								icon: "jobCertificate",
							},
						},
						desc: data.hamal_desc,
					},
					installer: {
						status: data.erector_status,
						options: {
							...JSON.parse(common),
							installerJobCertificate: {
								name: "erector_images",
								el: "image",
								value: data.erector_images,
								maxlength: 2,
								placeholder: "*上传职业证正副页*",
								icon: "jobCertificate",
							},
						},
						desc: data.erector_desc,
					},
				};
			});
		}

		switchTopTabBar(key: string) {
			this.tabKey = key;
		}

		operation(optionKey: string, e: AnyObject) {
			const { status, options } = this.viewModel[this.tabKey];
			if (status >= 1) return;

			const option = options[optionKey];
			switch (optionKey) {
				case "drivingLicense":
				case "transporterJobCertificate":
				case "installerJobCertificate":
					uni.chooseImage({
						count: option.maxlength - option.value.length,
						success: ({ tempFilePaths }) => {
							uni.showToast({ title: "uploading", icon: "loading" });
							(tempFilePaths as string[]).forEach(async (filePath) => {
								const [uploadFail, uploadRes]: any = await uni.uploadFile({
									url: $config.API_URL + "/upload",
									filePath,
									name: "file",
									header: {
										Authorization: Storage.get("authorization").access_token,
									},
								});

								if (uploadFail) {
									uni.showToast({
										title: uploadFail.errMsg,
										icon: "none",
									});
									return;
								}

								const { errcode, errmsg: title, data } = JSON.parse(uploadRes.data);

								if (errcode) {
									uni.showToast({
										title,
										icon: "none",
									});
									return;
								}
								option.value.push(filePath);
								option.data ? option.data.push(data.img) : (option.data = [data.img]);
							});
						},
					});
					break;
				default:
					option.value = option.data = e.detail.value;
					break;
			}
		}

		async tapPhotos(optionKey: string, current: any) {
			const { status, options } = this.viewModel[this.tabKey];
			if (status >= 1) return;

			const [showFail, result]: any = await uni.showActionSheet({
				itemList: ["预览", "删除"],
			});

			if (showFail) return;

			const option = options[optionKey];

			!result.tapIndex
				? uni.previewImage({ urls: option.value, current })
				: ["value", "data"].forEach((key) => option[key].splice(current, 1));
		}

		publish() {
			const { options } = this.viewModel[this.tabKey];
			const params: [string, AnyObject][] = [];
			const verifyParams = Object.values(options).every((option: any) => {
				params.push([
					option.name,
					Array.isArray(option.data) ? option.data.toString() : option.data,
				]);

				return Boolean(
					option?.data?.toString() ||
						uni.showToast({
							title: option.placeholder,
							icon: "none",
							success: () => false,
						})
				);
			});

			if (!verifyParams) return;

			this.$request
				.post("/user/join", {
					type: ["driver", "transporter", "installer"].indexOf(this.tabKey) + 1,
					...Object.fromEntries(params),
				})
				.then(({ errmsg: title }) => {
					uni.showToast({
						title,
						icon: "none",
						success: async () => {
							await sleep(1.5);
							uni.navigateBack({});
						},
					});
				});
		}
	}
</script>

<style lang="scss" scoped>
	// scss
	.tab {
		color: #666;
		padding: 10rpx;
		&.active {
			position: relative;
			color: #3ec483;
			font-weight: 500;
			&::after {
				content: "";
				position: absolute;
				bottom: 0;
				width: 80rpx;
				height: 4rpx;
				background-color: #3ec483;
			}
		}
	}
</style>